import React, { useState, useEffect } from 'react'
import DocumentTitle from 'react-document-title'
import { GroupStyle } from '../../style'
import { Modal, Toast } from 'antd-mobile'
import { getAllGroup } from '@api/group'
import { useHistory, useParams } from 'react-router-dom'
import { Timer } from '@common'
import { mixRoute } from '@/utils'
import { useSelector, useStore } from 'react-redux'
import { createPurchaseOrder, updateOrderAddress } from '@api/home'
import { selectedAddressAction } from '@store/actionCreators'
import { PopupStyle } from '../../../home/component/home/minGoodsDetail/style'


import { GroupGoodsItem } from '@common/goodsItem'

const pdz = 'https://res.lexiangpingou.cn/images/826/2020/11/yv1c5UPEXTArcxcLLcxXgttlEZG4L4.png'
const pdsb = 'https://res.lexiangpingou.cn/images/826/2020/11/BmC0LI4me4VRv24RkEnrz4tLEyl9VR.png'
const pdcg = 'https://res.lexiangpingou.cn/images/826/2020/11/POTVZsj7jOS7Sy4jDfL92JDfkGlfg4.png'
const pz = 'https://res.lexiangpingou.cn/images/826/2020/11/XBbxqB33PLvG2Z5n3B83ogv22xiO3Z.png'


const 新开一个团 = (props) => (
    < button className="bottom-share" onClick={e => { props.history.push(`/goodsdetail/${props.goodsid}`) }} >
        { props.groupstatus === '1' && '重新发起拼单'}
        { props.groupstatus === '2' && '发起新的拼单'}
    </button>
)

const JoinTuan = (props) => {

    const history = useHistory();
    const store = useStore();
    const params = useParams()
    const [joinModal, setjoinModal] = useState(false)
    const [goodsNum, setgoodsNum] = useState(1)

    var tuan_id = params.tuanid

    const { appConfig, defaultAddress } = store.getState()
    const { uniacid, isApplet } = appConfig

    const { goodsid, lacknum, pack_type, car_size, car_type, title, endtime } = props

    useEffect(() => {



    }, [joinModal, goodsNum])

    function isEndtime() {
        if (parseInt(endtime) > parseInt(new Date().getTime().toString().slice(0, -3))) {
            setjoinModal(!joinModal)
        } else {
            Toast.info('该团已过期', 1)
        }

    }


    return (
        <>
            < button className="share" onClick={e => { isEndtime() }} >
                立即参与拼单
            </button>

            <Modal
                visible={joinModal}
                onClose={e => { setjoinModal(!joinModal) }}
                maskClosable={true}
                transparent
                popup={true}
                animationType='slide-up'
                title="参与拼单"
                style={{
                    backgroundColor: 'white',
                    borderRadius: '.25rem .25rem 0 0'
                }}
            >
                <PopupStyle >
                    <div className="goods-option-popup" >
                        <div className="bottom" >
                            <div className="num flex-row">
                                <div className="num-limit">需求数量 {/*<span>{minDetail.min_num}起发</span>*/}  </div>
                                <div className="num-input">
                                    <div className="content flex-row">
                                        <div className="cube" onClick={e => { changeGoodsNum('reduce') }} > - </div>
                                        <input className="goodsnum" type="number" name="goodsNum" value={goodsNum} onChange={e => { handelInput(e) }} />
                                        <div className="cube" onClick={e => { changeGoodsNum('plus') }} > + </div>
                                    </div>
                                </div>
                            </div>
                            <button className="caigou" onClick={e => { pingtuan() }}>
                                参与拼单
                </button>
                        </div>
                    </div>
                </PopupStyle>
            </Modal>
        </>
    )

    function pingtuan() {

        let addressConfig = {
            deposit_orderno: '',
            province: defaultAddress.proc,
            city: defaultAddress.cityc,
            county: defaultAddress.countyc,
            detailed_address: defaultAddress.detailed_address
        }

        let config = {
            tuan_id,
            id: goodsid,
            cartType: car_type,
            cartSize: car_size,
            packType: pack_type,
            uniacid: uniacid,
            min_num: goodsNum, // 购买数量
            buy: '1', // 传 1 表示购买 ,
            specs: title,
        }

        createPurchaseOrder(config).then(res => {
            if (res.status === 200) {
                addressConfig.deposit_orderno = res.data
                updateOrderAddress(addressConfig).then(rex => {
                    // this.props.popupOnOff()
                    store.dispatch(selectedAddressAction({})) // 清除 选择地址
                    isApplet ? window.navigateToWebWiew(`/submit/${res.data}/${tuan_id}`) : history.push(`/submit/${res.data}/${tuan_id}`)
                })

            } else if (res.status === 400) {
                Toast.info(res.msg)
            }

        })


    }

    function changeGoodsNum(type) {
        // 改变购买商品数量
        if (type === 'reduce') {
            if (goodsNum <= 0) {
                Toast.info('不能再减啦', 1)
            } else {
                setgoodsNum(goodsNum - 1)
            }
        } else {

            if (goodsNum >= lacknum) {
                Toast.info('超出承载量', 1)
            } else {
                setgoodsNum(parseInt(goodsNum) + 1)
            }
        }
    }
    function handelInput(e) {
        // 保存输入的商品数量
        if (parseInt(e.target.value) > lacknum) {
            Toast.info('超出承载量', 1)
        } else {
            setgoodsNum(e.target.value)
        }
    }
}

// 拼团上半部分
const GroupInfo = (props) => {

    const history = useHistory()
    const { goods, neednum, lacknum, endtime, isMember, groupstatus, isApplet, tuanid, goodsid } = props

    const [isShareArray, setIsShareArray] = useState(false)

    return (
        <div className="group-info flex-column">

            <div className="goods-item">
                <GroupGoodsItem {...goods} />
            </div>
            <p className="tuanid">
                团号：{tuanid}
            </p>

            <p className="status-text">
                已拼{neednum - lacknum}件 {groupstatus === '3' && <cc> ，还剩 <span> {lacknum} </span> 件 </cc>}
            </p>

            <progress value={neednum - lacknum} max={neednum} />

            { groupstatus === '3' && <div className="lack-time-text">
                拼单时间剩余
            </div>
            }

            {
                groupstatus === '3' &&
                <div className="timer">
                    {endtime && <Timer value={endtime} width={'3.89rem'} />}
                </div>
            }


            {
                // 拼团中
                groupstatus === '3' && isMember === 1 && // 团长
                <button className="share" onClick={e => { setIsShareArray(!isShareArray) }} >
                    分享给好友，一起参与拼单
                </button>
            }

            {
                groupstatus === '3' && isMember === 0 && // 团员(未参团)
                <JoinTuan {...props} {...props.goods} />
            }

            {
                groupstatus === '3' &&
                <div className="gohome" onClick={e => {
                    mixRoute(history, '/')
                    // isApplet ? window.navigateToWebWiew('/') : history.push('/') 
                }}>
                    返回首页
                </div>
            }
            {
                groupstatus !== '3' &&
                <div className="底部团失败或团成功底部 flex-row global-bottom-fixed">
                    <button className="gohome-bottom" onClick={e => { 
                        mixRoute(history, '/')
                        // isApplet ? window.navigateToWebWiew('/') : history.push('/') 
                        }}>
                        返回首页
                    </button>
                    {
                        // 拼团失败
                        groupstatus === '1' && <新开一个团 groupstatus={groupstatus} history={history} goodsid={goodsid} />
                    }
                    {
                        // 拼团成功
                        groupstatus === '2' && <新开一个团 groupstatus={groupstatus} history={history} goodsid={goodsid} />
                    }
                </div>

            }

            { groupstatus === "1" && <img src={pdsb} alt="" className="tuan-status" />}
            { groupstatus === "2" && <img src={pdcg} alt="" className="tuan-status" />}
            { groupstatus === "3" && <img src={pdz} alt="" className="tuan-status" />}
            { groupstatus === "4" && <img src={pdcg} alt="" className="tuan-status" />}
            { isShareArray && <div className="share-array" onClick={e => { setIsShareArray(!isShareArray) }}>
                <img className="" src="https://res.lexiangpingou.cn/images/vip/sharejiantou.png" alt="" />
            </div>
            }

        </div >
    )



}

const GroupMemberList = (props) => {

    const { memberList, firstGroup, isMember, uniacid } = props

    function sortMyInFirst(memberList) {
        let aa = new Array()
        aa = memberList
        aa.shift()
        let my = {}
        let temp = aa[0]
        for (let i = 0; i < memberList.length; i++) {
            if (aa[i].uniacid === uniacid) {
                my = aa[i]
                aa[0] = my
                aa[i] = temp
            }
        }
        console.log(aa)

        return aa
    }

    return (

        <div className="group-member"
            style={
                isMember === 0 ? { filter: 'blur(5px)' } : {}
            }
        >
            {/* 团长 */}
            <div className="first-group flex-row">

                <div className="left flex-row">
                    <img src="https://res.lexiangpingou.cn/images/826/2020/10/Jrw73uRJjszsJJ3ujjZJVAjWvBVrbF.png" alt="" className="avatar" />
                    <div className="info">
                        <p className="name flex-row">
                            {firstGroup.name}
                            <img src={pz} alt="" className="first-logo" />
                        </p>
                        <p className="address">
                            {firstGroup.province}{firstGroup.city}{firstGroup.county}{firstGroup.detailed_address}
                        </p>
                    </div>
                </div>
                <div className="tel">
                    <a href={`tel:${firstGroup.phone}`}>
                        <img src="https://res.lexiangpingou.cn/images/826/2020/11/KkZl9JdG449ukN55156yY6al454k4G.png" alt="" />
                    </a>
                </div>
            </div>
            {/* 团员 */}
            <div className="group-list flex-column">
                {/* 可以做成轮播 */}
                {
                    sortMyInFirst(memberList).map((item, key) => (
                        <GroupMember my_uniacid={uniacid} key={key + item.deposit_paytime} {...item} />
                    ))
                }

            </div>
        </div>

    )
}

const GroupMember = (props) => {
    const { name, num, deposit_paytime, goodsname, uniacid, my_uniacid } = props

    return (
        <div className="item" style={my_uniacid !== uniacid ? { filter: 'blur(2px)' } : {}} >
            <div className="top flex-row">
                <div className="right flex-row">
                    <img src="https://res.lexiangpingou.cn/images/826/2020/10/Jrw73uRJjszsJJ3ujjZJVAjWvBVrbF.png" alt="" />
                    <div className="name"> {name} </div>
                </div>
                <div className="time-text"> {depositTiem(parseInt(deposit_paytime))} </div>
            </div>
            <div className="bottom flex-row">
                <p className="goods-name"> {goodsname} </p>
                <span className="num"> X{num} </span>
            </div>
        </div>

    )

    function depositTiem(des) {
        // 返回下单时间
        let now = parseInt(new Date().getTime().toString().slice(0, -3))
        let before = now - des
        let hour = parseInt(before / 3600)

        console.log(hour, before, now)

        if (hour > 24) {
            return parseInt(hour / 24) + '天前'
        } else if (hour < 1) {

            return parseInt(before / 60) + '分钟前'
        } else {
            return hour + '小时前'
        }
    }
}

const Group = (props) => {

    var params = useParams()
    const appConfig = useSelector(state => state.appConfig)
    const [groupData, setGroupData] = useState({})
    const { uniacid, isApplet } = appConfig
    useEffect(() => {

        getAllGroup({
            tuan_id: params.tuanid,
            uniacid: uniacid
        }).then(res => {
            console.log(res.data)
            if (res.status === 200) {
                setGroupData(res.data)
            }
        })

    }, [])

    return (
        <>
            <DocumentTitle title={props.route.title} />
            <GroupStyle>

                {/* 拼团详情 */}
                {groupData.group && <GroupInfo {...groupData.group} isApplet={isApplet} tuanid={params.tuanid} isMember={groupData.memOn} />}

                {/* 团员列表 */}
                {groupData.group_member && <GroupMemberList firstGroup={groupData.group_member[0]} uniacid={uniacid}
                    memberList={groupData.group_member} isMember={groupData.memOn} />}

            </GroupStyle>
        </>
    )
}


export default Group